const { Service } = require("uni-cloud-router");
const uniID = require('uni-id');
const response=require("../utils/response.js");
const db = uniCloud.database({
	spaceId: 'b33db069-91a2-42ff-a831-31fbd5a04b97'
});
const dbCmd = db.command;
const collection=db.collection("opendb-mall-goods");
const $ = db.command.aggregate;
module.exports = class GoodsService extends Service {
  async add(data){
  	const res=await collection.add(data);
		if(res.id){
			return response.success(res);
		}else{
			return response.fail('添加失败');
		}
  }
	async edit(id,data){
		const res=await collection.doc(id).update(data);
		if(res.updated>0){
			return response.success(res);
		}else{
			return response.fail('修改失败');
		}
	}
	async getOne(id){
		const res=await collection.aggregate().lookup({
			from: 'opendb-mall-sku',
			localField: '_id',
			foreignField: 'goods_id',
			as: 'skus',
		}).match({
			_id:id
		}).end();
		if(res.affectedDocs>=0){
			return response.success(res.data[0]);
		}else{
			return response.fail('查询失败');
		}
	}
  async list(data){
		const page_size=data.page_size||20
		const page_num=data.page_num||1
		const cate_id=data.cate_id
		const sort=data.sort||{_id:1}
		const where={}
		if(cate_id){
			where.category_id=cate_id
		}
		if(data.is_hot!=undefined){
			where.is_hot=data.is_hot
		}
		if(data.is_best!=undefined){
			where.is_best=data.is_best
		}
		if(data.is_new!=undefined){
			where.is_new=data.is_new
		}
		if(data.is_on_sale!=undefined){
			where.is_on_sale=data.is_on_sale
		}
		const res=await collection.aggregate().lookup({
			from: 'opendb-mall-sku',
			localField: '_id',
			foreignField: 'goods_id',
			as: 'skus',
		}).replaceRoot({
			newRoot: $.mergeObjects([ $.arrayElemAt(['$skus', 0]), '$$ROOT' ])
		}).match(where).sort(sort).limit(page_size).skip((page_num-1)*page_size).end();
		if(res.affectedDocs>=0){
			return response.success(res.data);
		}else{
			return response.fail('查询失败');
		}
  }
  async delete(ids){
  	return await collection.where({
			a: dbCmd.in(ids)
		}).remove();
  }
};